<script>
import _ from 'lodash'
import Draggable from 'vuedraggable'
import dict from '../../dictionary/setting-panel.js'
import { propertyChangeHandler } from '../mixins.js'

export default {
  props: ['id', 'fullField', 'shortField', 'value', 'multiple', 'model'],
  components: {
    Draggable
  },
  functional: true,
  render (h, context) {
    const { props } = context
    let modelClone = _.cloneDeep(props.model)
    let optionsClone = _.cloneDeep(props.value)
    const generateJsx = () => {
      if (props.multiple) {
        return (
          <checkbox-group
            value={ modelClone }
            on-on-change={ value => propertyChangeHandler(props.id, 'defaultValue', value, context) }
          >
            <Draggable
              element="ul"
              list={ optionsClone }
              options={{ group: { name: 'options' }, ghostClass: 'ghost' }}
            >
              {
                optionsClone.map((item) => {
                  return (
                    <li>
                    <checkbox value={ item.value }>
                      <i-input value={ item.value } on-on-change={ evt => { item.value = evt.target.value } } />
                    </checkbox>
                  </li>
                  )
                })
              }
            </Draggable>
          </checkbox-group>
        )
      } else {
        return (
          <radio-group
            value={ modelClone }
            on-on-change={ value => propertyChangeHandler('defaultValue', value, context) }
          >
            <Draggable
              element="ul"
              list={ optionsClone }
              options={{ group: { name: 'options' }, ghostClass: 'ghost' }}
            >
              {
                optionsClone.map((item) => {
                  return (
                    <li>
                      <radio label={ item.label || item.value } />
                      <i-input value={ item.value } on-on-change={ evt => { item.value = evt.target.value } } />
                    </li>
                  )
                })
              }
            </Draggable>
          </radio-group>
        )
      }
    }

    return (
      <form-item label={ dict[props.fullField] }>
        { generateJsx() }
      </form-item>
    )
  }
}
</script>
